#include "Acceptor.hh"

Acceptor::Acceptor(string ip, unsigned short port) 
    : _addr(ip, port){

}

void Acceptor::Ready() {
    Set_reuse_addr();
    Set_reuse_port();
    Bind();
    Listen();
}


int Acceptor::Accept() {
    int new_fd = ::accept(_sock_fd.Get_fd(), nullptr, nullptr);
    if(new_fd == -1){
        ::error(1, errno, "accept");
    }
    return new_fd;
}

Acceptor::~Acceptor() {

}

void Acceptor::Set_reuse_addr() {
    int opt = 1;
    if(::setsockopt(_sock_fd.Get_fd(), SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1){
        ::error(1, errno, "setsockopt");
    }
}

void Acceptor::Set_reuse_port() {
    int opt = 1;
    if(::setsockopt(_sock_fd.Get_fd(), SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)) == -1){
        ::error(1, errno, "setsockopt");
    }
}

void Acceptor::Bind() {
    if(::bind(_sock_fd.Get_fd(), (struct sockaddr*)_addr.Get_addrptr(), sizeof(struct sockaddr)) == -1){
        ::error(1, errno, "bind");
    }
}

void Acceptor::Listen() {
    if(::listen(_sock_fd.Get_fd(), 5) == -1){
        ::error(1, errno, "listen");
    }
}

int Acceptor::Get_fd() const{
    return _sock_fd.Get_fd();
}